/*
 * @Author: zy
 * @Date: 2021-10-21 09:15:56
 * @Last Modified by:   lt
 * @Last Modified time: 2021-10-25 17:21:12
 */

import React, { useState, useEffect, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Form, Space, Row, Col, Button, Pagination, Popconfirm, message, Input } from 'antd';
import styles from './index.less';
import ProTable from '@ant-design/pro-table';
import type { ActionType } from '@ant-design/pro-table';
import { DownOutlined, RightOutlined } from '@ant-design/icons/lib/icons';
import Modal from './components/modal/ClassificationManageModal';
import {
  getClassificationList,
  getClassificationInfo,
  getClassificationTypes,
  delClassification,
} from '@/services/classification';

import type {
  OptionClassificationInfoDataType,
  ClassificationItem,
} from '@/services/classification';

const ClassificationManage = () => {
  const [form] = Form.useForm(); // 表单对象
  const pageSizeOptions = ['5', '10', '15']; //分页选择范围
  const ref = useRef<ActionType>(); //tableRef

  const [modalVisible, setmodalVisible] = useState(false); // 设置modal是否显示
  const [page, setPage] = useState<number>(1); //设置当前页
  const [pageSize, setPageSize] = useState<number>(5); //设置每页记录数
  const [total, setTotal] = useState<number>(); //设置记录条数
  const [searchKey, setSearchKey] = useState<string>(); //设置搜索关键字
  const [modifyAid, setModifyAid] = useState<number>(-1); //设置数据的唯一标识（-1为新增）

  const [typeList, setTypeList] = useState<ClassificationItem[] | []>([]); //设置modal的TreeData选择器的数据
  const [modalData, setModalData] = useState<OptionClassificationInfoDataType | undefined>();

  /**
   * @description: 页面刷新（根据modal是否显示、当前页、每页记录数的变化进行页面刷新）
   */
  useEffect(() => {
    let mounted = true;
    if (mounted) {
      //Do Something
      ref.current?.reload();
    }
    return function cleanup() {
      mounted = false;
    };
  }, [page, pageSize]);

  /**
   * @description: 页面刷新（根据新增修改modal的变化且处于关闭状态时进行页面刷新）
   */
  useEffect(() => {
    let mounted = true;
    if (mounted) {
      //Do Something
      if (!modalVisible) {
        ref.current?.reload();
      }
    }
    return function cleanup() {
      mounted = false;
    };
  }, [modalVisible]);

  /**
   * @description: 获取分类信息（1、既可以返回所有数据，又可以根据aid进行查询；
   *                            2、设置modal的TreeData选择器的数据）
   */
  const getDataClassification = async (aid?: number) => {
    if (aid) {
      const params = { aid };
      const msg = await getClassificationInfo(params);
      setModalData(msg);
    }
    const data = await getClassificationTypes();
    setTypeList(data.data);
  };

  /**
   * @description: 查询提交（传入关键字数据并进行设置，刷新页面）
   */
  const onFinish = (values: { searchKey: string }) => {
    setSearchKey(values.searchKey);
    ref.current?.reload();
  };

  /**
   * @description: 查询重置(将关键字设置为空，重新渲染表单数据，刷新页面)
   */

  const onReset = () => {
    setSearchKey(undefined);
    form.resetFields();
    ref.current?.reload();
  };

  /**
   * @description: 新增分类（1、设置modal显示；
   *                        2、设置传给modal数据为空；
   *                        3、设置操作判别；
   *                        4、重新获取分类信息）
   */
  const onInsert = () => {
    setmodalVisible(true);
    setModalData(undefined);
    setModifyAid(-1);
    getDataClassification();
  };

  /**
   * @description: table数据请求（1、判断searchKey是否存在值，将判断后的数据传给相应后端
   *                             2、渲染返回数据（正常数据或查询数据），并进行提示）
   */
  const requestHandler = async () => {
    let msg;
    if (searchKey) {
      const params = { searchKey, page, pageSize };
      msg = await getClassificationList(params);
    } else {
      const params = { page, pageSize };
      msg = await getClassificationList(params);
    }
    if (msg?.code === 10000) {
      setTotal(msg.data.rowNumber);
      return {
        data: msg?.data?.list,
        success: true,
        total: msg?.data.rowNumber,
      };
    } else {
      message.error(msg ? msg.message : '网络异常');
      return {
        data: undefined,
        success: false,
        total: 0,
      };
    }
  };

  /**
   * @description: 分页设置（设置当前页和每页记录数）
   */

  const paginationChangeHandler = (_page: any, _pageSize: any) => {
    setPage(_page);
    setPageSize(_pageSize);
  };

  //table列
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 590,
      height: 56,
    },
    {
      title: '操作',
      dataIndex: 'isDelete',
      key: 'options',
      width: 538,
      height: 56,
      render: (text: any, record: any) => {
        return (
          <div>
            <Button
              name="columnEdit"
              type="link"
              size="small"
              onClick={async () => {
                const aid = record.aid;
                await getDataClassification(aid);
                setModifyAid(aid);
                setmodalVisible(true);
              }}
            >
              修改
            </Button>

            <Popconfirm
              title="你确认要删除该项数据吗？"
              onConfirm={async () => {
                const params = {
                  aid: record.aid,
                };
                const msg = await delClassification(params);
                if (msg?.code === 10000) {
                  ref.current?.reload();
                  message.success('删除成功');
                } else {
                  message.error(msg ? msg.message : '提交失败');
                }
              }}
              okText="确认"
              cancelText="取消"
              disabled={!record.isDelete}
            >
              <Button name="columnDelete" type="link" disabled={!record.isDelete} size="small">
                删除
              </Button>
            </Popconfirm>
          </div>
        );
      },
    },
  ];

  //搜索栏
  const searchLayout = () => {
    return (
      <div key="searchLayout">
        <Form form={form} onFinish={onFinish} layout="inline">
          <Form.Item name="searchKey" key="searchKey" className={styles.searchKey}>
            <Space>
              <span>分类名称：</span>
              <Input className={styles.searchLayoutInput} allowClear />
            </Space>
          </Form.Item>
          <Form.Item className={styles.searchBtn}>
            <Space>
              <Button name="searchResert" htmlType="button" onClick={onReset}>
                重置
              </Button>
              <Button name="searchQuery" type="primary" htmlType="submit">
                查询
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    );
  };

  //分页组件
  const afterTableLayout = () => {
    return (
      <Row justify="end">
        <Col className={styles.tableToolbar}>
          <Pagination
            current={page}
            pageSize={pageSize}
            total={total}
            showSizeChanger
            pageSizeOptions={pageSizeOptions}
            onChange={paginationChangeHandler}
          />
        </Col>
      </Row>
    );
  };

  return (
    <PageContainer>
      <Card className={styles.cardStyle}>{searchLayout()}</Card>
      <Card>
        <ProTable
          columns={columns}
          request={requestHandler}
          actionRef={ref}
          pagination={false}
          headerTitle={[
            <div key="tableTitle" className={styles.titleBox}>
              <span className={styles.titleText}>分类列表</span>
            </div>,
          ]}
          toolBarRender={() => [
            <Button type="primary" onClick={onInsert}>
              新增
            </Button>,
          ]}
          size="middle"
          search={false}
          options={{
            fullScreen: true,
            setting: false,
            density: false,
          }}
          rowKey="name"
          expandable={{
            defaultExpandAllRows: true,
            expandIcon: ({ expanded, onExpand, record }) =>
              record.children ? (
                expanded ? (
                  <DownOutlined
                    style={{ margin: ' 0px 15px' }}
                    onClick={(e) => onExpand(record, e)}
                  />
                ) : (
                  <RightOutlined
                    style={{ margin: ' 0px 15px' }}
                    onClick={(e) => onExpand(record, e)}
                  />
                )
              ) : (
                <span style={{ margin: ' 0px 23px' }} />
              ),
          }}
        />
        {afterTableLayout()}
      </Card>
      <Modal
        modifyAid={modifyAid}
        modalVisible={modalVisible}
        hideModal={() => {
          setmodalVisible(false);
        }}
        dataSource={modalData}
        treeData={typeList}
      />
    </PageContainer>
  );
};

export default ClassificationManage;
